package com.leyou.user.controller;

import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping
public class UserController {
    @Autowired
    private UserService userService;

    //校验用户名和手机号
    @GetMapping("/check/{data}/{type}")
    public ResponseEntity<Boolean> checkUsernameAndPhone(
            @PathVariable("data") String data, @PathVariable("type") Integer type) {

        return ResponseEntity.ok(userService.checkUsernameAndPhone(data, type));
    }

    //发送短信
    @PostMapping("/code")
    public ResponseEntity<Void> sendCheckCode(@RequestParam("phone") String phone) {
        userService.sendCheckCode(phone);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    //校验短信,   @Valid User user 由于User的name属性上有@Size(min = 4, max = 16) 要想生效就加这个注解
    @PostMapping("/register")
    public ResponseEntity<Void> register(@Valid User user, BindingResult result, @RequestParam("code") String code) {
        userService.register(user, code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    @GetMapping("/query")
    public ResponseEntity<UserDTO> findUserInfo(@RequestParam("username") String username,
                                @RequestParam("password") String password) {

        return ResponseEntity.ok(userService.findUserInfo(username, password));
    }
}
